/**
 *	   Contexto Logico do DroideGuide:
 * 	   ================================
 * 
 * 	Aqui construiremos  um banco de  dados
 *  com todos os pontos turisticos  e seus
 *  atributos relacionados como sono, fome,
 *  disposicao e humor.
 *  
 *   
 */

package br.ufmg.ubicomp.droidguide.context;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * -- Computacao Ubiqua -- Prof. Loureiro -- Leticia e Pollyanna
 * @author Leticia Decker de Sousa
 * @version 1.0
 * @since Agosto de 2008
 * @date 10/19/2008
 */

public class CreateDataBaseRoute {
    public static final String KEY_ID = "_id";
    public static final String KEY_NAME_TPOINT = "tourist_point";
    public static final String KEY_HUNGER = "hunger";
    public static final String KEY_MOOD = "mood";
    public static final String KEY_PROVISION = "provision";
    public static final String KEY_SLEEP = "sleep";

    private static final String TAG = "Tourist_Point";
    private DatabaseHelper dbLogicContext;
    private SQLiteDatabase lcDb;

	 /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
            "create table context (_id integer primary key autoincrement, "
          + "tourist_point text not null, hunger int not null, mood text not null,"
          +	" provision int not null, sleep int not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "context";
    private static final int DATABASE_VERSION = 2;

    private final Context dgCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS context");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     * Pega o contexto, necessario p comunicar com o Android
     */
    
    public CreateDataBaseRoute(Context ctx) {
        this.dgCtx = ctx;
    }

    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    
    public CreateDataBaseRoute open() throws SQLException {
    	dbLogicContext = new DatabaseHelper(dgCtx);
        lcDb = dbLogicContext.getWritableDatabase();
        
        return this;
    }
    
    public void close() {
    	dbLogicContext.close();
    }


    /**
     * Create a new note using the title and body provided. If the note is
     * successfully created return the new rowId for that note, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the note
     * @param body the body of the note
     * @return rowId or -1 if failed
     */
    public long createContext(String tourist_point, String hunger, String mood, String provision, String sleep) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME_TPOINT, tourist_point);
        initialValues.put(KEY_HUNGER, hunger);
        initialValues.put(KEY_MOOD, mood);
        initialValues.put(KEY_PROVISION, provision);
        initialValues.put(KEY_SLEEP, sleep);

        return lcDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the note with the given rowId
     * 
     * @param rowId id of note to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteContext(long rowId) {
    	
        return lcDb.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all notes in the database
     * 
     * @return Cursor over all notes
     */
    public Cursor fetchAllContext() {

        return lcDb.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_NAME_TPOINT, KEY_HUNGER, 
        		KEY_MOOD, KEY_PROVISION, KEY_SLEEP}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the note that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchContext(long rowId) throws SQLException {

        Cursor mCursor =    lcDb.query(true, DATABASE_TABLE, new String[] {KEY_ID,
                			KEY_NAME_TPOINT, KEY_HUNGER, KEY_MOOD, KEY_PROVISION,
                			KEY_SLEEP}, KEY_ID + "=" + rowId, null, null, null, 
                			null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public boolean updateNote(long rowId, int tourist_point, int hunger, String mood,
    													  int provision, int sleep) {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME_TPOINT, tourist_point);
        args.put(KEY_HUNGER, hunger);
        args.put(KEY_MOOD, mood);
        args.put(KEY_PROVISION, provision);
        args.put(KEY_SLEEP, sleep);

        return lcDb.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
    }
    
}


